package demo;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import keeper.control.Controller;
import keeper.event.EventListener;

/**
 * Servlet implementation class Demo
 */
public class Demo extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private static TimerListener timeListener = new TimerListener();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Demo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("get.");
		boolean isRun = timeListener.isRun();
		PrintWriter out = response.getWriter();
		if(isRun) {
			timeListener.setRun(false);
			out.write("start");
		} else {
			timeListener.setRun(true);
			new Thread(timeListener).start();
			out.write("stop");
		}
		if(out!=null) {
			out.close();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Post..");
		String msg = request.getParameter("msg");
		Controller.action(new SendMsg(msg),"msg");
	}
}

class SendMsg implements EventListener{
	private String msg;
	public SendMsg(String msg) {
		this.msg = msg;
	}
	@Override
	public void process(HttpServletRequest request, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			if(msg!=null){
				out.write(msg);
			}
		} catch (IOException e) {	
			e.printStackTrace();
		}
		finally{
			if(out != null) {
				out.close();
			}
		}		
	}
}

class TimerListener implements Runnable,EventListener{
	private boolean isRun = false;
	@Override
	public void run() {
		while(isRun) {
			System.out.println("run...");
			if(!Controller.action(this,"timer")){
				isRun = false;
				break;
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}	
	}
	@Override
	public void process(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			Date d = new Date();
			out.write(d.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(out != null) {
				out.close();
			}
		}
	}
	public boolean isRun() {
		return isRun;
	}
	public void setRun(boolean isRun) {
		this.isRun = isRun;
	}
	
}
